package top.wugy.blog.routes;

import com.jfinal.aop.Before;
import com.jfinal.kit.FileKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import top.wugy.blog.kits.BlogKit;
import top.wugy.blog.kits.Const;
import top.wugy.blog.model.TBlog;
import top.wugy.blog.model.TTag;
import top.wugy.blog.searcher.SearcherBean;
import top.wugy.blog.searcher.SearcherKit;
import top.wugy.blog.web.AuthInterceptor;

import java.io.File;
import java.util.Date;

public class BlogController extends BaseController {

    public void index() {
        Page<Record> blogPageList = TBlog.dao.blogList(isLogin(), getPageNum(), getPara("tag"), getPara("date"));
        setAttr("blogPage", blogPageList);
        render("/views/index.html");
    }

    /**
     * 文章发布页面
     */
    public void form() {
        Integer blogId = getParaToInt();
        Record blog;
        if (null != blogId) {
            blog = TBlog.dao.findBlog(blogId);
        } else {
            blog = new Record();
            blog.set("pub", true);
        }
        setAttr("blog", blog);
        setAttr("tags", TTag.dao.findAll());
        render("/views/blogForm.html");
    }

    /**
     * 发布文章
     */
    @Before(AuthInterceptor.class)
    public void publish() {
        TBlog blog = getModel(TBlog.class, "blog");
        String tagName = blog.getTag();
        TTag dao = TTag.dao;
        TTag tag = dao.findByName(tagName);
        if (null == tag) {
            tag = dao;
            tag.setName(tagName);
            tag.save();
        }
        Date now = BlogKit.now();
        SearcherBean bean = new SearcherBean.Builder().setTitle(blog.getTitle()).setTag(blog.getTag())
                .setContent(blog.getContent()).setCreateTime(now).build();
        if (null == blog.getId()) {
            blog.setCreateTime(now);
            blog.save();
            bean.setId(blog.getId());
            SearcherKit.addRecord(bean);
        } else {
            blog.update();
            bean.setId(blog.getId());
            SearcherKit.updateRecord(bean);
        }
        renderOk();
    }

    /**
     * 查看文章
     */
    public void view() {
        Integer blogId = getParaToInt();
        Record blog = TBlog.dao.findBlog(blogId);
        blog.set("content", BlogKit.md2Html(blog.get("content")));
        setAttr("blog", blog);
        render("/views/blogView.html");
    }

    @Before(AuthInterceptor.class)
    public void delete() {
        TBlog blog = getModel(TBlog.class, "blog");
        blog.setStatus(Const.DEL);
        blog.update();
        renderOk();
    }

    @Before(AuthInterceptor.class)
    public void uploadToCloud() {
        UploadFile file = getFile();
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(Const.QINIU_ACCESSKEY, Const.QINIU_SECRETKEY);
        UploadManager uploadManager = new UploadManager(cfg);
        String fileName = file.getOriginalFileName();
        try {
            File realFile = file.getFile();
            Response res = uploadManager.put(realFile, fileName, auth.uploadToken(Const.QINIU_BUCKET));
            if (res.isOK()) {
                FileKit.delete(realFile);
                renderOk(String.format("http://%s/%s", Const.QINIU_DOMAIN, fileName));
            }
        } catch (Exception e) {
            e.printStackTrace();
            render(Const.ERROR, "文件上传失败：" + e);
        }
    }

}
